﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace PipeSockets
{
    public class TcpConnection : AbstractConnection
    {
        private readonly Socket _socket;
        public TcpConnection(Socket socket, IProtocolParser protocolParser, Action<AbstractConnection, ReadOnlySequence<byte>> onMessageReceived, PipeOptions sendPipeOptions, PipeOptions receivePipeOptions) : base(protocolParser, sendPipeOptions, receivePipeOptions, socket.LocalEndPoint, socket.RemoteEndPoint)
        {
            _socket = socket;
            OnMessageReceived = onMessageReceived;
        }

        protected override async ValueTask<int> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
        {
            return await _socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken);
        }

        protected override async ValueTask<int> SendAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
        {
            return await _socket.SendAsync(buffer, SocketFlags.None, cancellationToken);
        }

        protected override Task OnStopAsync(CancellationToken cancellationToken = default)
        {
            _socket.Shutdown(SocketShutdown.Both);
            _socket.Close();
            return Task.CompletedTask;
        }
    }
}
